package middlewares

import (
	"github.com/gin-gonic/gin"
	"go-web/utils"
	"regexp"
)

// TokenCheck 检查token
// excludePath 排除要检测的URL的path路径，区分大小写, 支持正则表达式
// prefix 区分模块用的
func TokenCheck(excludePath []string, prefix string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if inPath(c.Request.URL.Path, excludePath) {
			c.Next()
			return
		}
		accessToken := c.Query("access_token")
		if accessToken == "" {
			utils.Json(c, 1000, "access_token is miss", nil)
			c.Abort()
			return
		}
		token := utils.NewToken(prefix)
		bindArg := token.GetBindArgByToken(accessToken)
		if bindArg == "" {
			utils.Json(c, utils.JsonAuthFailCode, "access_token is invalid", nil)
			c.Abort()
			return
		}
		c.Set("bindArg", bindArg)
		c.Next()
	}
}

// inPath
func inPath(currentPath string, excludePath []string) bool {
	for _, v := range excludePath {
		exist, _ := regexp.MatchString(v, currentPath)
		if exist {
			return true
		}
	}
	return false
}
